package com.sky.blue.xmltool.betwixt;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lzh
 * @date 2019/11/14 - 9:26
 */
public class BetwixtTest {

    @Test
    public void test1() throws Exception {

        //使用betwxit把java对象转为多层嵌套xml

        Clss c1 = new Clss();
        c1.setId(1);
        c1.setName("qewrr");

        Student s1 = new Student();
        s1.setName("aaa");
        s1.setScore(new Score(123));

        Student s2 = new Student();
        s2.setName("bbb");
        s2.setScore(new Score(213));
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        c1.setStudents(students);


        String resultStr = BetwixtUtil.objToXml(c1.getClass(), c1, true);
        System.out.println(resultStr);

        //将xml字符串保存为本地xml文件
        File file=new File("D:\\resultStr.xml");
        FileOutputStream fos=new FileOutputStream(file);
        IOUtils.write(resultStr , fos , "utf-8");

        /**
         * <?xml version="1.0" encoding="UTF-8"?>
         *   <clss id="1" name="qewrr">
         *     <students>
         *       <student>
         *         <name>aaa</name>
         *         <score>
         *           <mathScore>123</mathScore>
         *         </score>
         *       </student>
         *       <student>
         *         <name>bbb</name>
         *         <score>
         *           <mathScore>213</mathScore>
         *         </score>
         *       </student>
         *     </students>
         *   </clss>
         */

    }


    @Test
    public void test2() throws Exception{

        TestObj t22 = new TestObj("qr", 1234);


        //独立java对象(没有引用其他java对象)转xml
        String xmlstr = BetwixtUtil.objToXml(TestObj.class, t22, true);
        System.out.println(xmlstr);

        /**
         * <?xml version="1.0" encoding="UTF-8"?>
         *   <TestObj>
         *     <name>qr</name>
         *     <age>1234</age>
         *   </TestObj>
         */


    }


}
